﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Deeper.Common;
using System.Collections;
namespace Deeper.Engine
{
	public class ForeachTag : Tag
	{

		public ForeachTag(Document host)
			: base(host, "foreach")
		{
		}
		public override string ToString()
		{
			if (DataSource == null)
				DataSource = GetDatasource();
			String result = string.Empty;
			if (DataSource is IEnumerable)
			{
				foreach (object obj in DataSource as IEnumerable)
				{
					foreach (IElement el in Items)
					{
						if (el is EachItem)
						{
							result += obj.GetSubPropertyValue(((EachItem)el).Name).ToString();
						}
						else
							result += el.ToString();
					}
				}
			}
			return result;
		}

		public override void Render(System.IO.TextWriter writer)
		{

			writer.Write("");
		}

		public override void ProcessEndTag(ref Match match)
		{
			int charOffset = 0, offset = 0;

			if (!match.Groups["list"].IsNull())
				this.Name = match.Groups["list"].Value;
			charOffset = offset = match.Index + match.Length;
			match = null;
			#region 找到匹配结束标签
			while (offset < Host.TemplateContent.Length)
			{
				if ((match = Document.TagEndRegex.Match(Host.TemplateContent, offset)).Success)            //匹配到某个结束标签
				{
					Group gp = match.Groups["tag"];
					if (!gp.IsNull() && gp.Value == this.TagName)
					{
						this.Content = Host.TemplateContent.Substring(charOffset, match.Index - charOffset);
						GetEachItem();
						return;
					}
				}
				//处理偏移位置
				if (match != null && match.Success)
				{
					charOffset = offset = match.Index + match.Length;
					match = null;
				}
				else
				{
					offset++;
				}
			}
			#endregion

			if (match == null) throw new Exception(string.Format("{0}标签未闭合", Name));




		}

		protected void GetEachItem()
		{
			int charOffset = 0, offset = 0;
			Match match = null;
			while (offset < Content.Length)
			{
				if ((match = Document.EachItemRegex.Match(Content, offset)).Success)            //匹配到某个结束标签
				{
					Items.Add(new TextNode(Content.Substring(charOffset, match.Index - charOffset)));
					Items.Add(new EachItem(match.Groups["attr"].Value));

				}
				//处理偏移位置
				if (match != null && match.Success)
				{
					charOffset = offset = match.Index + match.Length;
					match = null;
				}
				else
				{
					offset++;
				}
			}
			Items.Add(new TextNode(Content.Substring(charOffset, Content.Length - charOffset)));
		}
	}
}
